package com.cep.client;

import java.nio.ByteBuffer;

import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class RoomListener implements OnItemSelectedListener {
	private static RoomListener instance = null;

	public static void init(TextView consoleOutputTV_) {
		instance = new RoomListener(consoleOutputTV_);
	}

	public static RoomListener instance() {
		return instance;
	}

	private TextView consoleOutputTV = null;

	public RoomListener(TextView consoleOutputTV_) {
		this.consoleOutputTV = consoleOutputTV_;
	}

	@Override
	public void onItemSelected(AdapterView<?> a0, View a1, int a2, long a3) {
		String room = a0.getItemAtPosition(a2).toString();
		String ownIP = UDPSender.instance().getLocalIpAddress();
		String name = NameWatcher.instance().getName();

		int cap = 8 + 2 + ownIP.getBytes().length + 2 + name.getBytes().length
				+ 2 + room.getBytes().length;

		ByteBuffer b = ByteBuffer.allocate(cap);

		// stream ID
		b.putLong(1);
		// IP address
		short s1 = (short) ownIP.getBytes().length;
		b.putShort(s1);
		b.put(ownIP.getBytes());
		// name
		short s2 = (short) name.getBytes().length;
		b.putShort(s2);
		b.put(name.getBytes());
		// room
		short s3 = (short) room.getBytes().length;
		b.putShort(s3);
		b.put(room.getBytes());

		if (UDPSender.instance().sendUDPMessage(b.array())) {
			consoleOutputTV.setText("New location sent for " + name + " from "
					+ ownIP + ":\n" + room);
		} else
			; // error-message is already printed
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
	}
}
